package user.web.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import user.service.IUserService;
import user.web.base.BaseResp;
import user.web.base.ErrorCode;

@Component
@Slf4j
public class UserAuthFilter extends HandlerInterceptorAdapter {

	@Autowired
	IUserService userService;
	
	protected String authParameterName = "e-token";
	
	protected static String INTERNAL_ERROR_TEXT = JSON.toJSONString(BaseResp.builder()
			.code(ErrorCode.INTERNAL_ERROR)
			.build());
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String token = request.getHeader(authParameterName);
		// 检验token是否过期
		if(!userService.isExpiredToken(token)) {
			log.error("the token : {} is expired", token);
			writeJSON(response, BaseResp.builder()
					.code(ErrorCode.TOKEN_EXPIRED)
					.cause("Expired Token")
					.build());
			return false;
		}
		
		return true;
	}

	protected void writeJSON(HttpServletResponse resp, Object obj) {
		if (resp == null) {
			return;
		}
		resp.setContentType("text/plain;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");

		PrintWriter writer;

		try {
			writer = resp.getWriter();
			writer.write(JSON.toJSONString(obj));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
